package com.sc.web.article;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sc.dal.model.ParamMap;
import com.sc.dal.model.article.Article;
import com.sc.dal.model.system.UserFormMap;
import com.sc.service.article.ArticleService;
import com.sc.util.adapter.ConfigBeanAdapter;
import com.sc.util.data.Constants;
import com.sc.util.data.DataUtil;
import com.sc.util.data.FileUtil;
import com.sc.util.exception.ExceptionEnum;
import com.sc.util.exception.ScBizException;
import com.sc.web.BaseController;
import com.sc.web.plugin.PageView;

@Controller
@RequestMapping(value="article")
public class ArticleContorller extends BaseController{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private ArticleService articleService;
	
	/**
	 * 
	 * @param model   查询关于我们 
	 * @param pageNow 添加类型9
	 * @param pageSize 
	 * @param column
	 * @param sort
	 * @return 返回到关于我们页面 (路径参照菜单页面)
	 * @throws Exception
	 */
    @RequestMapping("about_us")
    public String about(Model model,String pageNow, String pageSize, String column, String sort) throws Exception {
	    Article article = new Article();
	    article.setAtype("9");
	    List<Article> articleList = articleService.selectByParam(article);
	    if(articleList!=null && articleList.size()>0){
	    	model.addAttribute("article",articleList.get(0));
	    }
		return "article/about_us";
   }
	/**
	 * 
	 * @param model 添加res及type类型
	 * @param pageNow 把数据存入pageNow
	 * @param pageSize
	 * @param column
	 * @param sort
	 * @return 直接返回一个jsp页面
	 * @throws Exception
	 */
	@RequestMapping("list")
	public String list(Model model,String pageNow, String pageSize, String column, String sort) throws Exception {
		model.addAttribute("res",findByRes());
		model.addAttribute("aType", ArticleTypeEnum.values());
		return "article/list";
	}
	/**
	 * 
	 * @param id
	 * @param model 用model添加文章内容、type类型 以及id
	 * @return 判断如果是修改文章内容就返回到edit页面
	 * 如果不是的话就返回到添加
	 * 
	 */
	
	@RequestMapping(value="/addOrEdit")
	public  String addOrEdit(Integer id,Model model){
		if(id!=null){
			Article article=articleService.selectByPrimaryKey(id);
			model.addAttribute("article", article);
			model.addAttribute("aType", ArticleTypeEnum.values());
			model.addAttribute("id", id);
			return "article/edit";
		}
		model.addAttribute("aType", ArticleTypeEnum.values());
		return "article/add";
	}
	/**
	 *          添加关于我们文本信息
	 * @param pic
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/saveArticle")
	@ResponseBody
	public Map<String, Object> saveArticle(String id, String content, HttpServletRequest request){
		Map<String,Object> resultMap = new HashMap<String, Object>();
		Article article=new Article();
		try {
			//获取管理员信息
			UserFormMap userFormMap=(UserFormMap) SecurityUtils.getSubject().getSession().getAttribute("userSession");

			article.setContent(content);
			if(StringUtils.isBlank(id)){
				article.setTitle("关于我们");
				article.setAtype("9");
				article.setCreater(userFormMap.getStr("accountName"));
				article.setCreateTime(new Date());
				article.setIsDelete(Constants.IS_DELETEA);
				articleService.insert(article);
				resultMap.put("id", article.getId());
			}else{
				article.setId(Integer.parseInt(id));
				article.setModifier(userFormMap.getStr("accountName"));
				article.setModifyTime(new Date());
				articleService.updateByPrimaryKeySelective(article);
			}
			
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			return resultMap;
		}
	}
	/**
	 * 添加页面的内容以及存储
	 * @param pic
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/addOrUpdateArticle")
	@ResponseBody
	public Map<String, Object> uploadPic(MultipartFile pic,HttpServletRequest request){
		Map<String,Object> resultMap = new HashMap<String, Object>();
		Article article=new Article();
		//指定图片的存储路径
		String matchPath="article/";
		try {
			//获取管理员信息
			UserFormMap userFormMap=(UserFormMap) SecurityUtils.getSubject().getSession().getAttribute("userSession");
			//获取文章的信息
			String title=request.getParameter("title");
			String author=request.getParameter("author");
			String atype=request.getParameter("atype");
			String content=request.getParameter("content");
			content=URLDecoder.decode(content,"utf-8");
			String id=request.getParameter("id");
			try {
				content=URLDecoder.decode(content, "utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			article.setTitle(title);
			article.setAtype(atype);
			article.setAuthor(author);
			article.setContent(content);
			article.setCreater(userFormMap.getStr("accountName"));
			article.setCreateTime(new Date());
			article.setIsDelete(Constants.IS_DELETEA);
			String imgUrl=FileUtil.uploadByFile(pic, "",matchPath, ConfigBeanAdapter.fileSaveAddress);
			if(imgUrl!=null&&!"".equals(imgUrl)&&!"1".equals(imgUrl)&&!"2".equals(imgUrl)){				
				article.setPic(imgUrl);
			}
			if(id==null){
				articleService.insert(article);
			}else{
				article.setId(Integer.parseInt(id));
				articleService.updateByPrimaryKeyWithBLOBs(article);
			}
			
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			return resultMap;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			return resultMap;
		}
	}
	@RequestMapping(value="/selectList")
	@ResponseBody
	public PageView selectList(HttpServletRequest request,String pageNow, String pageSize, String column, String sort){
		Map<String,Object> resultMap = new LinkedHashMap<String,Object>();
		
		try{
			ParamMap paramMap = getFormMap(ParamMap.class);	
			String title=request.getParameter("title");
			String atype=request.getParameter("atype");
			paramMap = toFormMap(paramMap, pageNow, pageSize,paramMap.getStr("orderby"));
			paramMap.put("title", title);
			paramMap.put("atype", atype);
			paramMap.put("column", column);
			paramMap.put("sort", sort);
			List<Article> articleList = this.articleService.selectList(paramMap);
			for (Article article : articleList) {
				ArticleTypeEnum[] aTypes=ArticleTypeEnum.values();
				article.setPic(ConfigBeanAdapter.fileAccessAddress+article.getPic());
				for (ArticleTypeEnum aType : aTypes) {
					if(aType.getValue().equals(article.getAtype())){
						article.setAtype(aType.getDesc());
					}
				}
			}
			pageView.setRecords(articleList);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			logger.info("查询轮播图数据成功!");
		}catch(Exception e){
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.error("查询轮播图数据异常:"+e);
			throw new ScBizException("查询轮播图数据异常！", e);
		}
		return pageView;
	}
	@ResponseBody
	@RequestMapping("deleteEntity")
	public String deleteEntity(){
		try {
			String ids = getPara("ids");
			String[] idArr=ids.split(",");
			for (String string : idArr) {
				Article article=new Article();
				article.setId(Integer.parseInt(string));
				article.setIsDelete(Constants.IS_DELETEB);
				article.setModifyTime(new Date());
				articleService.updateByPrimaryKeySelective(article);
			}
			return "\"success\"";
		} catch (Exception e) {
			logger.error("查询商品数据异常"+e);
			throw new ScBizException("查询商品数据异常！", e);
		}
	}
}
